using Admin2025.Domain.Entities;
using Admin2025.Domain.Repositories;
using Admin2025.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace Admin2025.infrastructure.Repositories;

/// <summary>
/// 通用EF仓储实现，提供基本的增删改查操作。
/// </summary>
/// <typeparam name="T">实体类型，必须继承自EntityBase。</typeparam>
public class EfRepository<T> : IRepository<T> where T : EntityBase
{
    private readonly AdminDbContext _db;
    private readonly DbSet<T> _tb;

    /// <summary>
    /// 构造函数，注入数据库上下文。
    /// </summary>
    /// <param name="db">AdminDbContext实例。</param>
    public EfRepository(AdminDbContext db)
    {
        _db = db;
        _tb = db.Set<T>();
    }

    /// <summary>
    /// 获取所有实体列表。
    /// </summary>
    /// <returns>实体集合。</returns>
    public async Task<IEnumerable<T>> GetAllAsync()
    {
        var list = await _tb.ToListAsync();
        return list;
    }

    /// <summary>
    /// 根据主键ID获取实体。
    /// </summary>
    /// <param name="id">实体ID。</param>
    /// <returns>实体对象或null。</returns>
    public async Task<T?> GetByIdAsync(Guid id)
    {
        var obj = await _tb.FindAsync(id);
        return obj;
    }

    /// <summary>
    /// 新增实体。
    /// </summary>
    /// <param name="entity">要新增的实体。</param>
    /// <returns>新增后的实体。</returns>
    public async Task<T> CreateAsync(T entity)
    {
        var obj = await _tb.AddAsync(entity);
        await _db.SaveChangesAsync();
        return obj.Entity;
    }

    /// <summary>
    /// 更新实体。
    /// </summary>
    /// <param name="entity">要更新的实体。</param>
    public async Task UpdateAsync(T entity)
    {
        _tb.Update(entity);
        await _db.SaveChangesAsync();
    }

    /// <summary>
    /// 逻辑删除实体（标记为已删除）。
    /// </summary>
    /// <param name="entity">要删除的实体。</param>
    public async Task DeleteAsync(T entity)
    {
        entity.IsDeleted = true;
        entity.UpdatedAt = DateTime.UtcNow;
        _tb.Update(entity);
        await _db.SaveChangesAsync();
    }
}